import Avatar from '@/components/Avatar';
import CheckBox from '@/components/CheckBox';
import { Button } from '@taroify/core';
import PageContainer from '@/components/PageContainer';
import { useDeviceListStore, useDeviceShare } from '@/hooks';
import useBoolean from '@/hooks/useBoolean';
import useEvent from '@/hooks/useEvent';
import { cancelDeviceShareToUsers, fetchDeviceShareUsers } from '@/services/share';
import { isSameDevice } from '@/utils';
import { GStyleSheet, DynamicColors } from '@/utils/DarkMode';
import { Image, ScrollView, Text, View } from '@tarojs/components';
import deviceShareModel from '@/models/deviceShare';
import Taro, { useRouter } from '@tarojs/taro';
import i18n from 'i18n-js';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useMemo, useState, useCallback } from 'react';
import manageIcon from '../images/user_manage.png';
import noUserIcon from '../images/noUser.png';
import StopShareAlert from '../shareList/container/StopShareAlert';

const dstyles = GStyleSheet.create({
  container: {
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
  },
  header: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    fontSize: 16,
    margin: '30rpx 30rpx 0',
  },
  cancelButton: {
    color: DynamicColors.tintColor
  },
  icon: {
    width: 16,
    height: 16,
    margin: -10,
    padding: 10,
  },
  users: {
    flex: 1
  },
  user: {
    margin: '24rpx 30rpx',
    height: 80,
    padding: '0 40rpx',
    display: 'flex',
    alignItems: 'center',
    background: '#fff',
    borderRadius: 9,
  },
  avatar: {
    width: 44,
    height: 44,
    // borderRadius: '50%',
    marginRight: 18,
  },
  content: {
    flex: 1,
    display: 'flex',
    flexDirection: 'column',
  },
  name: {
    fontSize: 16,
    height: 20,
  },
  checkbox: {
    width: 20,
    height: 20,
  },
  owner: {
    color: '#A6A6A6',
    fontSize: 12,
    marginTop: 2,
  },
  buttons: {
    position: 'fixed',
    left: 0,
    right: 0,
    bottom: 34,
    textAlign: 'center',
  },
  shareTime: {
    color: '#959595',
    fontSize: 12,
    lineHeight: '34rpx',
    marginTop: 2,
  },
  noUserImage: {
    width: 230,
    height: 110,
    marginBottom: 20,
  },
  noUserTip: {
    color: DynamicColors.subTitleTextColor,
    fontSize: 16,
  }
});

type Params = {
  pk: string;
  mac: string;
}

type IUser = GetResponseData<typeof fetchDeviceShareUsers> extends (infer R)[] ? R : any;

interface UserProps {
  data: IUser,
  selected: boolean;
  isManageMode: boolean;
  onPress(u: IUser): void;
}

const User: React.FC<UserProps> = React.memo(({
  data,
  selected,
  isManageMode,
  onPress,
}) => {
  const styles = dstyles.useDynamicStyle();

  const handlePress = useEvent(() => {
    isManageMode && onPress(data);
  });

  const nicknameAndMobile = useMemo(() => {
    if (!data.nickname) {
      return data.mobile || data.email || i18n.t('UNKNOW_USER');
    }
    return `${data.nickname}(${data.mobile || data.email})`
  }, [data.mobile, data.nickname, data.email])

  return (
    <View style={styles.user} onClick={handlePress}>
      <Avatar src={data.avatar} style={styles.avatar} />
      <View style={styles.content}>
        <Text style={styles.name} className='ellipsisText'>{nicknameAndMobile}</Text>
        <Text style={styles.shareTime} className='ellipsisText'>{`分享时间: ${data.shareTime}`}</Text>
      </View>
      {
        isManageMode && (
          <CheckBox style={styles.checkbox} checked={selected} />
        )
      }
    </View>
  )
})

const SharedUsers = () => {
  const router = useRouter<Params>();
  const devices = useDeviceListStore();
  const deviceShare = useDeviceShare();
  const [isManageMode, { setFalse: exitManageMode, setTrue: enterManageMode }] = useBoolean();
  const [selectedUsers, setSelectedUsers] = useState<IUser[]>([]);
  const [users, setUsers] = useState<IUser[]>([]);
  const [stopAlertShow, setStopAlertShow] = useState(false)

  const { pk, mac } = router.params;

  const handleManage = useEvent(() => {
    if (users.length > 0) {
      enterManageMode();
    }
  });

  const closeStopAlert = useCallback(() => {
    setStopAlertShow(false)
  }, [])

  const showStopAlert = useCallback(() => {
    setStopAlertShow(true)
  }, [])

  const device = useMemo(() => {
    return devices.data.find(d => isSameDevice(d, { productKey: pk, mac }));
  }, [devices.data, pk, mac]);

  const fetchUsers = useEvent(() => {
    if (!device?.mac || !device?.productKey) {
      setUsers([]);
      setSelectedUsers([]);
      return;
    }
    fetchDeviceShareUsers(device.mac, device.productKey).then((res) => {
      if (!res.success || !res.data) {
        return;
      }
      setUsers(res.data);
    })
  })

  const goToAddShare = useCallback(async () => {
    if (device) {
      deviceShareModel.setSelectedDevices([device]);
      const res = await deviceShareModel.createDeviceShareRecord();
      if (!res.success || !res.data) {
        return;
      }
      Taro.navigateTo({
        url: `/pages/share/modes/index?shareId=${res.data}`,
      });
    } else {
      // 设备不见了
      console.log('设备找不到了')
    }
  }, [device]);


  useEffect(() => fetchUsers(), [fetchUsers])

  const selectUser = useEvent((user: IUser) => {
    const index = selectedUsers.findIndex(u => u.userId === user.userId);
    index < 0
      ? setSelectedUsers([...selectedUsers, user])
      : setSelectedUsers([...selectedUsers.slice(0, index), ...selectedUsers.slice(index + 1)])
  })

  const styles = dstyles.useDynamicStyle();

  const isOwner = useMemo(() => {
    return !(device && deviceShare.receiveList.find(r => isSameDevice(r, device)))
  }, [deviceShare.receiveList, device]);

  const cancelUsers = useEvent(async () => {
    closeStopAlert()
    if (selectedUsers.length === 0) {
      exitManageMode();
      return;
    }
    Taro.showLoading();
    const res = await cancelDeviceShareToUsers({
      mac,
      productKey: pk,
      userIds: selectedUsers.map(u => u.userId),
    }).finally(() => {
      Taro.hideLoading();
    });
    if (res.success) {
      fetchUsers();
      deviceShare.fetchList();
      exitManageMode();
    }
  });

  const getRightButton = () => {
    if (!isOwner) return <View></View>
    if (isManageMode) return <Text onClick={exitManageMode} style={styles.cancelButton}>{i18n.t("CANCEL")}</Text>
    return <Image src={manageIcon} style={styles.icon} onClick={handleManage} />
  }

  return (
    <PageContainer title={i18n.t('DEVICE_SHARED_MANAGE')}>
      {!!device && (
        <View style={styles.container}>
          <View style={styles.header}>
            <Text>{i18n.t(isOwner ? 'I_SHARED' : 'DEVICE_USERS')}</Text>
            {getRightButton()}
          </View>
          <ScrollView style={styles.users}>
            {
              users.map(u => (
                <User
                  key={u.userId}
                  data={u}
                  isManageMode={isManageMode}
                  selected={!!selectedUsers.find(su => su.userId === u.userId)}
                  onPress={selectUser}
                />
              ))
            }
            {(!users || users.length == 0) && (
              <View className='centerFlex' style={{ flexDirection: 'column', marginTop: 150 }}>
                <Image src={noUserIcon} style={styles.noUserImage} />
                <Text style={styles.noUserTip}>{i18n.t('UNSHARE_ANYONE')}</Text>
              </View>
            )}
          </ScrollView>
          <View style={styles.buttons}>
            {isManageMode ? (
              <Button
                variant='outlined'
                shape='round'
                color='danger'
                onClick={showStopAlert}
                style={{ marginLeft: 20, marginRight: 20, backgroundColor: 'rgba(0,0,0,0)' }}
              >
                {i18n.t('STOP_SHARE')}
              </Button>
            ) : (
              <Button
                variant='contained'
                shape='round'
                color='primary'
                onClick={goToAddShare}
                style={{ marginLeft: 20, marginRight: 20 }}
              >
                {i18n.t('ADD_DEVICE_SHARE')}
              </Button>
            )}
          </View>
        </View>
      )}
      <StopShareAlert visible={stopAlertShow} onClose={closeStopAlert} onConfirm={cancelUsers} />
    </PageContainer>
  )
}

export default observer(SharedUsers);
